﻿#region Usings
using System;
using System.Xml;
using InfoService.Enums;
using InfoService.Feeds;
using InfoService.GUIConfiguration;
using InfoService.Twitter;
using InfoService.Utils;
using InfoService.Weather;
using InfoService.RecentlyAdded;
using MediaPortal.Configuration;
using MediaPortal.Dialogs;
using MediaPortal.GUI.Library;
using MediaPortal.Profile;
using WeatherConnector;
#endregion

namespace InfoService
{
    [PluginIcons("InfoService.GUIConfiguration.images.InfoService_icon_enabled.png", "InfoService.GUIConfiguration.images.InfoService_icon_disabled.png")]
    public sealed class InfoServiceCore : GUIWindow, ISetupForm
    {
        #region Variables
        public const int GUIInfoServiceId = 16000;
        private static readonly Logger Logger = Logger.GetInstance();
        #endregion

        #region Properties
        public static string UserPluginName { get; set; }
        #endregion

        #region ISetupForm Members

        public string PluginName()
        {
            return "InfoService";
        }

        public string Description()
        {
            return "InfoService is a plugin for that provides weather, feed and twitter informations on the home screen. It has also a feed reader and a twitter client built in. The plugin is for MediaPortal users and skinners who want to have some information on their MediaPortal homescreen.";
        }

        public string Author()
        {
            return "edsche, SilentException";
        }

        public void ShowPlugin()
        {
            ConfigForm config = new ConfigForm();
            config.ShowDialog();
        }

        public bool CanEnable()
        {
            return true;
        }


        public bool GetHome(out string strButtonText, out string strButtonImage,
  out string strButtonImageFocus, out string strPictureImage)
        {
            strButtonText = UserPluginName;
            strButtonImage = String.Empty;
            strButtonImageFocus = String.Empty;
            strPictureImage = String.Empty;
            return true;
        }

        public bool DefaultEnabled()
        {
            return true;
        }

        public bool HasSetup()
        {
            return true;
        }

        public int GetWindowId()
        {
            return GUIInfoServiceId;
        }

        #endregion

        #region Constructor
        public InfoServiceCore()
        {
            GetID = GUIInfoServiceId;
        }
        #endregion

        #region Overrides
        public override bool SupportsDelayedLoad
        {
            get
            {
                return false;
            }
        }
        protected override void OnPageLoad()
        {
            if (FeedService.Enabled && TwitterService.Enabled)
            {
                InfoServiceUtils.SetProperty("#currentmodule", "InfoService");
                GUIDialogMenu dlg = (GUIDialogMenu) GUIWindowManager.GetWindow((int) Window.WINDOW_DIALOG_MENU);
                if (dlg != null)
                {

                    dlg.Reset();
                    dlg.SetHeading(InfoServiceUtils.GetLocalizedLabel(28));
                    dlg.Add("Feeds");
                    dlg.Add("Twitter");
                    dlg.DoModal(GUIWindowManager.ActiveWindow);
                    Logger.WriteLog("Opened InfoService from Home menu. Showing InfoService moduls...", LogLevel.Info, InfoServiceModul.InfoService);
                    GUIWindowManager.ShowPreviousWindow();
                    if (dlg.SelectedId > 0)
                    {
                        switch (dlg.SelectedLabelText)
                        {
                            case "Feeds":
                                Logger.WriteLog("Selected to show the Feeds window", LogLevel.Info, InfoServiceModul.InfoService);
                                GUIWindowManager.ActivateWindow(GUIWindows.GUIFeed.GUIFeedId, true);
                                break;
                            case "Twitter":
                                Logger.WriteLog("Selected to show the Twitter window", LogLevel.Info, InfoServiceModul.InfoService);
                                GUIWindowManager.ActivateWindow(GUIWindows.GUITwitter.GUITwitterId, true);
                                break;
                        }
                    }

                }
                else
                {
                    Logger.WriteLog("Error creating GUIDialogMenu Object. Please contact plugin author!", LogLevel.Info, InfoServiceModul.InfoService);
                }
            }
            else
            {
                if (FeedService.Enabled) GUIWindowManager.ActivateWindow(GUIWindows.GUIFeed.GUIFeedId, true);
                else if(TwitterService.Enabled) GUIWindowManager.ActivateWindow(GUIWindows.GUITwitter.GUITwitterId, true);
            }
            base.OnPageLoad();
        }

        public override bool Init()
        {
            InfoServiceUtils.InitLog();
            InfoServiceUtils.LoadLocalization();
            InfoServiceUtils.InitAllProperties();

            XmlDocument xml = new XmlDocument();
            xml.Load(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"));

            #region Default settings

            if (xml.DocumentElement != null)
            {
                if (xml.DocumentElement.SelectSingleNode("//section[@name='InfoService']") == null)
                {
                    Logger.WriteLog("InfoService is used first time. Adding example feed and enabled weather", LogLevel.Debug, InfoServiceModul.InfoService);
                    using (Settings settings = new Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
                    {
                        settings.SetValue("InfoService", "Feed1Url", "http://www.team-mediaportal.com/index2.php?option=com_rss&feed=RSS1.0&no_html=1");
                        settings.SetValue("InfoService", "Feed1Image", "");
                        settings.SetValue("InfoService", "Feed1Title", "MediaPortal News");
                        settings.SetValue("InfoService", "Feed1DefaultZoom", "100");
                        settings.SetValueAsBool("InfoService", "FeedTickerEnabled", true);
                        settings.SetValueAsBool("InfoService", "FeedRandomFeedOnUpdate", false);
                        settings.SetValue("InfoService", "FeedSeparator", "::");
                        settings.SetValue("InfoService", "FeedItemsCountPerFeed", 3);
                        settings.SetValue("InfoService", "FeedItemsCount", 10);
                        settings.SetValue("InfoService", "FeedRefreshInterval", 30);
                        settings.SetValueAsBool("InfoService", "FeedUpdateOnStartup", true);
                        settings.SetValueAsBool("InfoService", "FeedShowItemPublishTime", true);
                        settings.SetValue("InfoService", "FeedTickerMask", "%itemtitle%");
                        settings.SetValueAsBool("InfoService", "WeatherEnabled", true);
                        settings.SetValue("InfoService", "WeatherRefreshInterval", 60);
                        settings.SetValueAsBool("InfoService", "WeatherUpdateOnStartup", true);
                        settings.SetValue("InfoService", "FeedLastCacheDeletion", DateTime.Today.ToShortDateString());
                    }
                }
            }

            #endregion

            #region SkinSettings
            Logger.WriteLog("Loading skin settings from infoservice.xml, skin settings have priority", LogLevel.Debug, InfoServiceModul.SkinSettings);
            InfoServiceSkinSettings.InfoServiceSkinSettingsInstance.loadSkinSettings(GUIGraphicsContext.Skin + @"\infoservice.xml");
            #endregion

            #region MediaPortal.xml settings
            Logger.WriteLog("Loading settings from MediaPortal.xml, skin settings will take priority", LogLevel.Debug, InfoServiceModul.InfoService);
            using (Settings settings = new Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
            {
                UserPluginName = settings.GetValueAsString("InfoService", "PluginName", "InfoService");

                #region Feeds
                if (settings.GetValueAsBool("InfoService", "FeedTickerEnabled", false))
                {
                    Logger.WriteLog("Init FeedService", LogLevel.Info, InfoServiceModul.InfoService);

                    FeedService.SetupFeeds();
                    FeedService.RefreshInterval = settings.GetValueAsInt("InfoService", "FeedRefreshInterval", 15);
                    FeedService.RandomFeedOnStartup = settings.GetValueAsBool("InfoService", "FeedRandomFeedOnStartup", false);
                    FeedService.StartupFeedIndex = settings.GetValueAsInt("InfoService", "FeedStartupFeedIndex", 0);
                    FeedService.UpdateOnStartup = settings.GetValueAsBool("InfoService", "FeedUpdateOnStartup", true);
                    FeedService.ShowPublishTime = settings.GetValueAsBool("InfoService", "FeedShowItemPublishTime", true);
                    FeedService.TickerMask = settings.GetValueAsString("InfoService", "FeedTickerMask", "%itemtitle%");
                    FeedService.DeletionInterval = (DeleteCache)Enum.Parse(typeof(DeleteCache), settings.GetValueAsString("InfoService", "FeedDeletionInterval", "Week"));
                    FeedService.Items = Convert.ToByte(settings.GetValueAsInt("InfoService", "FeedItemsCount", 10));
                    FeedService.Separator = settings.GetValueAsString("InfoService", "FeedSeparator", "::");
                    FeedService.ItemsPerFeed = Convert.ToByte(settings.GetValueAsInt("InfoService", "FeedItemsCountPerFeed", 3));
                    FeedService.RandomFeedOnUpdate = settings.GetValueAsBool("InfoService", "FeedRandomFeedOnUpdate", false);
                    FeedService.MediaPortalStartup = true;
                    FeedUpdater.SetupUpdater();
                    Logger.WriteLog("Load feeds...", LogLevel.Info, InfoServiceModul.Feed);
                    for (int i = 1; i <= 200; i++)
                    {
                        string feedurl = settings.GetValueAsString("InfoService", "Feed" + i + "Url", "ERROR");
                        if (feedurl == "ERROR") break;
                        string feedimage = settings.GetValueAsString("InfoService", "Feed" + i + "Image", "No Image");
                        string feedtitle = settings.GetValueAsString("InfoService", "Feed" + i + "Title", "No Title");
                        int feeddefaultzoom = settings.GetValueAsInt("InfoService", "Feed" + i + "DefaultZoom", 100);
                        FeedService.AddFeed(feedurl, feedtitle, feeddefaultzoom, feedimage);
                    }
                    InfoServiceUtils.SetProperty("#infoservice.feed.separator", FeedService.Separator);
                    InfoServiceUtils.SetProperty("#infoservice.feed.enabled", FeedService.Enabled.ToString());
                    Logger.WriteLog("Successfully initiated FeedService", LogLevel.Info, InfoServiceModul.Feed);

                }
                else Logger.WriteLog("FeedService is not enabled", LogLevel.Debug, InfoServiceModul.InfoService);
                #endregion

                #region Weather
                if (settings.GetValueAsBool("InfoService", "WeatherEnabled", false))
                {
                    Logger.WriteLog("Init WeatherService", LogLevel.Info, InfoServiceModul.Weather);
                    string location = settings.GetValueAsString("weather", "location", string.Empty);

                    //Location is empty -> That means the user was never in the MP Weather GUI.
                    if(string.IsNullOrEmpty(location))
                    {
                        //Then use the ID from code0
                        
                        location = settings.GetValueAsString("weather", "code0", string.Empty);
                        Logger.WriteLog("No location ID found in the location field of mediaportal.xml. Will using the one of code0 -> " + location, LogLevel.Warning, InfoServiceModul.Weather);
                        settings.SetValue("weather", "location", location);
                        WeatherService.CurrentLocationId = location;
                    }
                    bool success = WeatherService.SetupWeather(location, settings.GetValueAsString("weather", "temperature", "C") == "C"
                                                    ? TemperatureFormat.Grad
                                                    : TemperatureFormat.Fahrenheit,
                                                "1117489152", "93c392356341e017");
                    if (success)
                    {
                        WeatherService.RefreshInterval = settings.GetValueAsInt("InfoService", "WeatherRefreshInterval", 30);
                        WeatherService.UpdateOnStartup = settings.GetValueAsBool("InfoService", "WeatherUpdateOnStartup", true);
                        InfoServiceUtils.SetProperty("#infoservice.weather.enabled", WeatherService.Enabled.ToString());
                        WeatherUpdater.SetupUpdater();
                        Logger.WriteLog("Successfully initiated WeatherService", LogLevel.Info, InfoServiceModul.Weather);
                    }
                    else
                    {
                        Logger.WriteLog("Cannot initialize WeatherService. See above for errors", LogLevel.Error, InfoServiceModul.Weather); 
                    }
                }
                else Logger.WriteLog("WeatherService is not enabled", LogLevel.Debug, InfoServiceModul.InfoService);
                #endregion

                #region Twitter
                if (settings.GetValueAsBool("InfoService", "TwitterTickerEnabled", false))
                {
                    Logger.WriteLog("Init TwitterService",LogLevel.Info, InfoServiceModul.Twitter);
                    bool success = TwitterService.SetupTwitter(settings.GetValueAsString("InfoService", "TwitterUser", ""), settings.GetValueAsString("InfoService", "TwitterPassword", ""),
                                                               settings.GetValueAsString("InfoService", "TwitterPin", ""), settings.GetValueAsString("InfoService", "TwitterTokenValue", ""),
                                                               settings.GetValueAsString("InfoService", "TwitterTokenSecret", ""));
                    if(success)
                    {
                        
                        TwitterService.UpdateOnStartup = settings.GetValueAsBool("InfoService", "TwitterUpdateOnStartup", true);
                        TwitterService.RefreshInterval = settings.GetValueAsInt("InfoService", "TwitterRefreshInterval", 15);
                        TwitterService.Separator = settings.GetValueAsString("InfoService", "TwitterSeparator", "::");
                        TwitterService.Items = Convert.ToByte(settings.GetValueAsInt("InfoService", "TwitterItemsCount", 10));
                        TwitterService.UseHomeTimeline = settings.GetValueAsBool("InfoService", "TwitterUseHomeTimeline", false);
                        TwitterService.UsePublicTimeline = settings.GetValueAsBool("InfoService", "TwitterUsePublicTimeline", false);
                        TwitterService.UseUserTimeline = settings.GetValueAsBool("InfoService", "TwitterUseUserTimeline", false);
                        TwitterService.UseFriendsTimeline = settings.GetValueAsBool("InfoService", "TwitterUseFriendsTimeline", false);
                        TwitterService.UseMentionsTimeline = settings.GetValueAsBool("InfoService", "TwitterUseMentionsTimeline", false);
                        TwitterService.UseRetweetedByMeTimeline = settings.GetValueAsBool("InfoService", "TwitterUseRetweetedByMeTimeline", false);
                        TwitterService.UseRetweetedToMeTimeline = settings.GetValueAsBool("InfoService", "TwitterUseRetweetedToMeTimeline", false);
                        TwitterService.UseRetweetsOfMeTimeline = settings.GetValueAsBool("InfoService", "TwitterUseRetweetsOfMeTimeline", false);
                        TwitterService.TickerMask = settings.GetValueAsString("InfoService", "TwitterTickerMask", "%message%");
                        TwitterService.DeletionInterval = (DeleteCache)Enum.Parse(typeof(DeleteCache), settings.GetValueAsString("InfoService", "TwitterDeletionInterval", "Day"));
                        TwitterService.PostWatchingVideos = settings.GetValueAsBool("InfoService", "TwitterUpdateStatusOnVideoStart", false);
                        TwitterService.PostWatchMask = settings.GetValueAsString("InfoService", "TwitterWatchMask", "I'm watching %video% on my MediaPortal HTPC!");
                        TwitterService.PostUsingMovingPictures = settings.GetValueAsBool("InfoService", "TwitterUpdateStatusUsingMovingPictures", false);
                        TwitterService.PostUsingTVSeries = settings.GetValueAsBool("InfoService", "TwitterUpdateStatusUsingMPTVSeries", false);
                        TwitterService.PostUsingMyVideos = settings.GetValueAsBool("InfoService", "TwitterUpdateStatusUsingMyVideo", false);
                        InfoServiceUtils.SetProperty("#infoservice.twitter.separator", TwitterService.Separator);
                        InfoServiceUtils.SetProperty("#infoservice.twitter.enabled", TwitterService.Enabled.ToString());
                        TwitterUpdater.SetupUpdater();
                        Logger.WriteLog("Successfully initiated TwitterService", LogLevel.Info, InfoServiceModul.Twitter);
                    }
                    else
                    {
                        Logger.WriteLog("Cannot initialize TwitterService. See above for errors", LogLevel.Error, InfoServiceModul.Twitter);
                    }
                }
                else Logger.WriteLog("TwitterService is not enabled", LogLevel.Debug, InfoServiceModul.InfoService);
                #endregion
            }
            #endregion

            RecentlyAddedUpdater.SetupUpdater();
            UpdateTimer.SetTimer();

            #region Load infoservice.xml
            Logger.WriteLog("Loading InfoService GUI skin file from " + GUIGraphicsContext.Skin + @"\infoservice.xml", LogLevel.Debug, InfoServiceModul.InfoService);
            bool loadedSkinSuccess = Load(GUIGraphicsContext.Skin + @"\infoservice.xml");
            if (loadedSkinSuccess) Logger.WriteLog("Loaded InfoService GUI skin file successful", LogLevel.Debug, InfoServiceModul.InfoService);
            else
            {
                if (!System.IO.File.Exists(GUIGraphicsContext.Skin + @"\infoservice.xml"))
                {

                    Logger.WriteLog("Loading Twitter GUI skin file failed. Skin file " + GUIGraphicsContext.Skin + @"\infoservice.xml" + " doesn't exist.", LogLevel.Debug, InfoServiceModul.InfoService);
                }
                else
                {
                    Logger.WriteLog("Loading InfoService GUI skin file failed. Unknown error.", LogLevel.Debug, InfoServiceModul.InfoService);
                }
            }
            return loadedSkinSuccess;
            #endregion
        }


        public override void DeInit()
        {
            RecentlyAddedUtils.SaveLastRecentlyAddedItems();
            Logger.CloseLog();
            base.DeInit();
        }
        #endregion
    }
}


